<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>mvvmVueObserver</title>
</head>
<body>

</body>
<script type="text/javascript">

	function Dep() {
	    this.subs = [];
	}

	Dep.prototype = {
	    addSub: function(sub) {
	        this.subs.push(sub);
	    },
	    notify: function() {
	        this.subs.forEach(function(sub) {
	            sub.update();
	        });
	    }
	};

	var data = {name: 'kindeng',sex:'1',obj:{title:'aaa'}};
	observe(data);
	data.name = 'dmq'; // 哈哈哈，监听到值变化了 kindeng --> dmq
	data.sex = '2'; // 哈哈哈，监听到值变化了 kindeng --> dmq
	data.obj.title = 'bbb'; // 哈哈哈，监听到值变化了 kindeng --> dmq
	
	function observe(data) {
	    if (!data || typeof data !== 'object') {
	        return;
	    }
	    // 取出所有属性遍历
	    Object.keys(data).forEach(function(key) {
	        defineReactive(data, key, data[key]);
	    });
	};

	function defineReactive(data, key, val) {

		var dep = new Dep();

	    observe(val); // 监听子属性
	    Object.defineProperty(data, key, {
	        enumerable: true, // 可枚举
	        configurable: false, // 不能再define
	        get: function() {
	            return val;
	        },
	        set: function(newVal) {

	        	if(val == newVal) return;

	            console.log('哈哈哈，监听到值变化了 ', val, ' --> ', newVal);
	            val = newVal;

	            dep.notify();// 通知所有订阅者
	        }
	    });
	}

	console.log(new Dep())

</script>
</html>